//
//  BDAddressViewController.m
//  BadBoy
//
//  Created by wen on 2017/2/20.
//  Copyright © 2017年 niusaibing. All rights reserved.
//

#import "BDAddressViewController.h"
#import "BDAddressTableViewCell.h"
#import "BDAddAddressViewController.h"
#import "BDUserModel.h"


@interface BDAddressViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) UIButton *addAddressBtn;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = kBDColorGray;
    if ([self.titleString isNotEmpty]) {
        self.title = self.titleString;
    }else {
        self.title = ASLocalizedString(@"收货地址");
    }

    [self.view addSubview:self.addAddressBtn];
    [self bindRAC];
    [self requesetDatasource];
}

- (void)bindRAC{
    [[self.addAddressBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BDAddAddressViewController *newAddressVC = [[BDAddAddressViewController alloc]init];
        [self.navigationController pushViewController:newAddressVC animated:YES];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"refreshAddressList" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        self.datasource = nil;
        [self requesetDatasource];
    }];
}

- (void)requesetDatasource{
    [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    NSString *url = [NSString stringWithFormat:@"%@user/address", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        self.datasource  = [BDUserAddressModel mj_objectArrayWithKeyValuesArray:x];
        [self.tableview reloadData];
        if (self.datasource.count == 0) {
            [self setTableiewFooterViewStateFor:self.tableview datasourceCount:0];
        }
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDAddressTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BDUserAddressModel *addressModel = self.datasource[indexPath.section];
    
    __weak BDAddressViewController *weakSelf = self;
    
    [cell configeWithModel:addressModel morenBlock:^{
        NSString *url = [NSString stringWithFormat:@"%@user/address/default/%@", KBDBaseURL, @(addressModel.address_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_PUT:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        
        [signal subscribeNext:^(id  _Nullable x) {
            for (BDUserAddressModel *mod in self.datasource) {
                if (mod.isDefault == YES) {
                    mod.isDefault = NO;
                }
            }
            addressModel.isDefault = YES;
            BDUserModel *user = [BDUserModel getCurrentUser];
            user.address_id = addressModel.address_id;
            [user saveCurrentUser];
            [weakSelf.tableview reloadData];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager showBriefAlert:ASLocalizedString(@"网络不好，设置失败")clickHidden:NO clickBlock:nil];
        }];
    }editBlock:^{
        BDAddAddressViewController *addVc = [[BDAddAddressViewController alloc] init];
        addVc.addressModel = weakSelf.datasource[indexPath.section];
        [weakSelf.navigationController pushViewController:addVc animated:YES];
    } deletedBlock:^{
        NSString *url = [NSString stringWithFormat:@"%@user/address/%@", KBDBaseURL, @(addressModel.address_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_DELETE:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        
        [signal subscribeNext:^(id  _Nullable x) {
            BDUserModel *user = [BDUserModel getCurrentUser];
            if (user.address_id == addressModel.address_id) {
                user.address_id = 0;
                [user saveCurrentUser];
            }
            [weakSelf.datasource removeObject:addressModel];
            [weakSelf.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager showBriefAlert:ASLocalizedString(@"网络不好，删除失败")clickHidden:NO clickBlock:nil];
        }];
    }];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.chooseAddressBlock) {
        [self.navigationController popViewControllerAnimated:YES];
        self.chooseAddressBlock(self.datasource[indexPath.section]);
    }
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDButtonHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor = [UIColor clearColor];
        _tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (UIButton *)addAddressBtn{
    if (!_addAddressBtn) {
        _addAddressBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, kBDScreenHeight - kBDButtonHeight, kBDScreenWidth, kBDButtonHeight)];
        _addAddressBtn.backgroundColor = [UIColor whiteColor];
        [_addAddressBtn setTitle:ASLocalizedString(@" 新增地址")forState:UIControlStateNormal];
        [_addAddressBtn setImage:[UIImage imageNamed:@"xinzeng@2x"] forState:UIControlStateNormal];
        [_addAddressBtn setTitleColor:KBDColorDeepBlue forState:UIControlStateNormal];
    }
    return _addAddressBtn;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
